/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.hk.shop.web.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.act.utils.ExpressUtil;
import com.thinkgem.jeesite.modules.hk.shop.entity.order.HkShopUserOrder;
import com.thinkgem.jeesite.modules.hk.shop.entity.shop.HkShopExpress;
import com.thinkgem.jeesite.modules.hk.shop.entity.shop.HkUserShop;
import com.thinkgem.jeesite.modules.hk.shop.service.order.HkShopExpressService;
import com.thinkgem.jeesite.modules.hk.shop.service.order.HkShopUserOrderService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * 用户订单管理Controller
 *
 * @author 罗天文
 * @version 2018-08-22
 */
@Controller
@RequestMapping(value = "${adminPath}/shop/order/hkShopUserOrder")
public class HkShopUserOrderController extends BaseController {

    private static final String EXPRESS_CACHE = "expressCache";

    @Autowired
    private HkShopUserOrderService hkShopUserOrderService;
    @Autowired
    private HkShopExpressService hkShopExpressService;

    @ModelAttribute
    public HkShopUserOrder get(@RequestParam(required = false) String id) {
        HkShopUserOrder entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = hkShopUserOrderService.get(id);
        }
        if (entity == null) {
            entity = new HkShopUserOrder();
        }
        return entity;
    }

    @RequiresPermissions("shop:order:hkShopUserOrder:view")
    @RequestMapping(value = {"list", ""})
    public String list(HkShopUserOrder hkShopUserOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
        HkUserShop hkUserShop = new HkUserShop();
        hkUserShop.setId(UserUtils.getShopId());
        hkShopUserOrder.setShop(hkUserShop);
        Page<HkShopUserOrder> page = hkShopUserOrderService.findPage(new Page<HkShopUserOrder>(request, response), hkShopUserOrder);
        model.addAttribute("page", page);
        return "hk/shop/order/hkShopUserOrderList";
    }

    @RequiresPermissions("shop:order:hkShopUserOrder:view")
    @RequestMapping(value = "form")
    public String form(HkShopUserOrder hkShopUserOrder, Model model) {
        model.addAttribute("hkShopUserOrder", hkShopUserOrder);
        return "hk/shop/order/hkShopUserOrderForm";
    }

    @RequiresPermissions("shop:order:hkShopUserOrder:edit")
    @RequestMapping(value = "save")
    public String save(HkShopUserOrder hkShopUserOrder, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, hkShopUserOrder)) {
            return form(hkShopUserOrder, model);
        }
        hkShopUserOrderService.save(hkShopUserOrder);
        addMessage(redirectAttributes, "保存用户订单管理成功");
        return "redirect:" + Global.getAdminPath() + "/shop/order/hkShopUserOrder/?repage";
    }

    @RequiresPermissions("shop:order:hkShopUserOrder:edit")
    @RequestMapping(value = "delete")
    public String delete(HkShopUserOrder hkShopUserOrder, RedirectAttributes redirectAttributes) {
        hkShopUserOrderService.delete(hkShopUserOrder);
        addMessage(redirectAttributes, "删除用户订单管理成功");
        return "redirect:" + Global.getAdminPath() + "/shop/order/hkShopUserOrder/?repage";
    }

    /**
     * 导出订单数据
     *
     * @param hkShopUserOrder
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("shop:order:hkShopUserOrder:view")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(HkShopUserOrder hkShopUserOrder, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户订单数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<HkShopUserOrder> page = hkShopUserOrderService.findCoupon(new Page<HkShopUserOrder>(request, response, -1), hkShopUserOrder);
            new ExportExcel("用户订单数据", HkShopUserOrder.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出优惠券用户订单失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/shop/shop/hkShopCoupon/list?repage";
    }

    /**
     * 添加物流信息
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("shop:order:hkShopUserOrder:edit")
    @RequestMapping(value = "logistics")
    public String logistics(HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
        boolean flag = false;
        String company = request.getParameter("company");
        String waybillNum = request.getParameter("waybillNum");
        String orderNum = request.getParameter("orderNum");
        Date deliverTime = DateUtils.parseDate(request.getParameter("deliverTime"));

        HkShopUserOrder hkShopUserOrder = new HkShopUserOrder();
        //已发货
        hkShopUserOrder.setState("4");
        hkShopUserOrder.setCourier(company);
        hkShopUserOrder.setCouriernumber(waybillNum);
        hkShopUserOrder.setDelivertime(deliverTime);
        hkShopUserOrder.setOrdernumber(orderNum);
        try {
            flag = hkShopUserOrderService.logistics(hkShopUserOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag) {
            addMessage(redirectAttributes, orderNum + "--" + "订单发货成功");
            return "redirect:" + Global.getAdminPath() + "/shop/order/hkShopUserOrder/?repage";
        } else {
            return null;
        }
    }

    /**
     * 获取快递公司
     *
     * @param request
     * @param response
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("shop:order:hkShopUserOrder:view")
    @RequestMapping(value = "getExpressCompay")
    @ResponseBody
    public void getExpressCompay(HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
        PrintWriter out = null;
        response.setCharacterEncoding("utf-8");
        try {
            List<HkShopExpress> expressList = hkShopExpressService.getExpressCompany();
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(expressList));
            out = response.getWriter();
            out.print(jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }


    /**
     * 获取快递信息
     *
     * @param request
     * @param response
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("shop:order:hkShopUserOrder:view")
    @RequestMapping(value = "getExpress")
    @ResponseBody
    public String getExpress(HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
        PrintWriter out = null;
        response.setCharacterEncoding("utf-8");

        String orderNumber = request.getParameter("orderNumber");
        String expressCompany = request.getParameter("express");
//        String orderNumber = "260034815902";
//        String expressCompany = "zhongtong";
        try {

            Object jsonData = CacheUtils.get(EXPRESS_CACHE,orderNumber.trim() + expressCompany.trim());
            if (jsonData == null || jsonData.equals("")) {
                jsonData = ExpressUtil.getExpress(expressCompany, orderNumber);
                CacheUtils.put(EXPRESS_CACHE,orderNumber.trim() + expressCompany.trim(), jsonData);
            }
            out = response.getWriter();
            out.print(jsonData);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
        return null;
    }

}